<?php
Page::$need_view=true;
$agency = get_user_agency();
$uid = Session::get('mainuid');
$user = (new Model('user'))->where(['id' => $uid])->find();
//
// send_sms('18839136081', '尊敬的客户您好，您的短信验证码是:113548');
//
if (Request::post()) {
  Page::$need_view=false;
  header('Content-Type:application/json');
  // 计算总价格
  $buy_num=intval($_POST['num']);
  $total_price = $buy_num * $agency->sms_price;
  // 判断购买条件
  if ($user->balance < $total_price) {
    sendResponse([
      'status' => 'error',
      'msg' => '余额不足'
    ], true);
  }
  $user->balance = $user->balance - $total_price;
  $user->surplus_sms = $user->surplus_sms + $buy_num;
  $user->save();
  // 生成购买记录
  $buy_rec=new Model('sms_buy_record');
  $buy_rec->ctime=time();
  $buy_rec->uid=$uid;
  $buy_rec->total_price=$total_price;
  $buy_rec->buy_num=$buy_num;
  $buy_rec->save();
  // 完成购买，返回结果
  sendResponse([
    'status' => 'success',
    'msg' => '购买成功',
  ], true);
}